﻿using System;
using System.Linq;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Modules.ACTP.Components;

namespace ASPNETVN.PORTAL.Modules.ACTP.Controls
{
    public partial class AddEditTeam : AddEditItemControl
    {
        protected override void OnInit(EventArgs e)
        {
            this.ButtonUpdate = btnUpdate;
            this.ButtonDelete = btnDelete;
            this.ButtonCancel = btnCancel;

            this.Update += AddEditTeam_Update;
            this.Delete += AddEditTeam_Delete;
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                ddlTeamLeader.DataSource = Employee.SelectCollectionAll(this.ModuleID).Select(x => new { x.EmployeeID, Title = "(Code: " + x.EmployeeCode + ") " + x.FirstName + " " + x.LastName });
                ddlTeamLeader.DataBind();
 
                if (this.ItemID > 0)
                {
                    Components.Team team = Components.Team.Load(this.ItemID);
                    if (team != null)
                    {
                        txtTitle.Text = team.Title;
                        ddlTeamLeader.SelectedValue = team.TeamLeaderID.ToString();
                        txtDescription.Text = team.Description;
                    }
                }
                else
                {
                    btnDelete.Visible = false;
                }
            }
        }

        void AddEditTeam_Update(object sender, EventArgs e)
        {
            Components.Team team = new Components.Team();
            if (this.ItemID > 0)
            {
                team = Components.Team.Load(this.ItemID);
            }

            team.ModuleID = this.ModuleID;
            team.TeamLeaderID = Convert.ToInt32(ddlTeamLeader.SelectedValue);
            team.Title = txtTitle.Text;
            team.Description = txtDescription.Text;

            // Insert.
            if (this.ItemID == 0)
            {
                this.ItemID = team.Insert();
            }
            // Update.
            else
            {
                team.TeamID = this.ItemID;
                team.Update();
            }

            // Go back.
            this.ReturnToReferrerPage();

        }

        void AddEditTeam_Delete(object sender, EventArgs e)
        {
            if (this.ItemID > 0)
            {
                Components.Team.DeleteTeam(this.ItemID);
                // Go back.
                this.ReturnToReferrerPage();
            }
        }
    }
}
